package rs.belex.belexdroid.activities;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import rs.belex.belexdroid.R;
import rs.belex.belexdroid.beans.interfaces.Share;
import rs.belex.belexdroid.beans.interfaces.ShareChange;
import rs.belex.belexdroid.services.impl.ksoap2.ShareProviderKsoap2Impl;
import rs.belex.belexdroid.services.interfaces.IShareProvider;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Base.ChartAxis.LabelsMode;
import com.artfulbits.aiCharts.Base.ChartAxis.ValueType;
import com.artfulbits.aiCharts.Types.ChartTypes;

public class ChartingActivity extends Activity {

	private static String TAG = ChartingActivity.class.getSimpleName();

	private final static int ABOUT_ITEM_ID = 1;
	private String symbol;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		symbol = getIntent().getStringExtra("symbol");

		ChartView chartView = new ChartView(this);
		ChartArea area = chartView.addArea();

		ChartSeries series = new ChartSeries("Trgovanje", ChartTypes.Line);

		SortedMap<Date, Double> date_price = provideData();

		Calendar currTime = Calendar.getInstance();
		Calendar timeAxis = Calendar.getInstance();
		timeAxis.setTime(date_price.firstKey());
		timeAxis.set(Calendar.MINUTE, 0);

		Calendar change = Calendar.getInstance();
		Calendar nextChange = Calendar.getInstance();

		Iterator<Date> iter = date_price.keySet().iterator();
		/** initialize time */
		if (iter.hasNext())
			change.setTime(iter.next());
		if (iter.hasNext())
			nextChange.setTime(iter.next());

		/** Make a scale for time period from 10.00 till 13.00 */
		timeAxis.set(Calendar.HOUR_OF_DAY, 10);
		while (timeAxis.get(Calendar.HOUR_OF_DAY) < 13) {
			if (timeAxis.after(change) && timeAxis.before(nextChange)) {
				series.getPoints().addDate(timeAxis.getTime(),
						date_price.get(change.getTime()));
			} else if (timeAxis.after(nextChange)) {
				change.setTime(nextChange.getTime());
				if (iter.hasNext())
					nextChange.setTime(iter.next());
			} else if (timeAxis.before(currTime)) {
				series.getPoints().addDate(timeAxis.getTime(),
						date_price.get(change.getTime()));
			}
			timeAxis.add(Calendar.MINUTE, 10);
		}
		for (Date date : date_price.keySet()) {
			series.getPoints().addDate(date, date_price.get(date));
		}

		area.getDefaultXAxis().setValueType(ValueType.Date);
		area.getDefaultXAxis().setLabelsMode(LabelsMode.SeriesLabels);
		area.getDefaultXAxis().setFormat("HH:mm");

		SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
		String date = df.format(change.getTime());
		area.getDefaultYAxis().setTitle("Cena na dan " + date);

		series.setShowLabel(true);

		chartView.getSeries().add(series);

		series.setArea(area.getName());

		setContentView(chartView);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu
				.add(0, ABOUT_ITEM_ID, 0,
						getString(R.string.about_menu_item_title));
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog result = null;
		Builder builder;

		switch (id) {
		case ABOUT_ITEM_ID:
			builder = new AlertDialog.Builder(this);

			builder.setTitle(R.string.about_menu_item_title);
			builder.setMessage(R.string.dlg_about_msg);

			builder.setPositiveButton("Ok", null);

			result = builder.create();
			break;

		default:
			result = super.onCreateDialog(id);
			break;
		}

		return result;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case ABOUT_ITEM_ID:
			showDialog(ABOUT_ITEM_ID);
			return true;

		default:
			return false;
		}
	}

	public SortedMap<Date, Double> provideData() {
		IShareProvider provider = new ShareProviderKsoap2Impl();
		Share share = provider.getShare(symbol);
		Calendar calendar = Calendar.getInstance();
		switch (calendar.get(Calendar.DAY_OF_WEEK)) {
		case Calendar.SATURDAY:
			calendar.add(Calendar.DAY_OF_WEEK, -1);
			break;
		case Calendar.SUNDAY:
			calendar.add(Calendar.DAY_OF_WEEK, -2);
			break;
		default:
			if (!(calendar.get(Calendar.HOUR_OF_DAY) >= 10)) {
				Log.i(TAG, "Getting yesterdays stock price values");
				calendar.add(Calendar.DAY_OF_WEEK, -1);
			}
			break;
		}
		List<ShareChange> changes = provider.getChangesOnDate(share, calendar
				.getTime());

		SortedMap<Date, Double> date_price = new TreeMap<Date, Double>();

		for (ShareChange change : changes) {
			Double price = share.getValue()
					+ change.getRoundDouble().doubleValue();
			Date date = change.getTime();
			date_price.put(date, price);
		}
		return date_price;
	}

}
